package com.declum.peyar.client;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Headers {
	Map<String, String> headers = new HashMap<String, String>();

	public boolean parseLine(String data) {
		String[] part = data.split("\\s*:\\s*");
		if (part.length == 2) {
			this.headers.put(part[0], part[1].trim());
			return true;
		} else {
			return false;
		}
	}

	public void parseResponse(String data) throws HeaderNotProper {
		if (data.endsWith("\r\n\r\n")) {
			String[] part = data.split("\n");
			for (String line : part) {
				line = line.trim();
				if (!line.equals("")) {
					this.parseLine(line);
				}
			}
		} else {
			throw new HeaderNotProper("Header is not complete");
		}
	}

	/**
	 * Set a value to a header
	 * 
	 * @param header
	 * @param value
	 */
	public void setHeader(String header, String value) {
		this.headers.put(header, value);
	}

	/**
	 * Return the value of a header specified
	 * 
	 * @param header
	 * @return
	 */
	public String getHeader(String header) {
		return this.headers.get(header);
	}

	public String getHeaders() {
		String value = "";
		Entry<String, String> entry;
		Iterator<Entry<String, String>> iterator = this.headers.entrySet()
				.iterator();
		while (iterator.hasNext()) {
			entry = iterator.next();
			value += entry.getKey() + ": " + entry.getValue() + "\r\n";
		}
		return value + "\r\n";
	}

	@Override
	public String toString() {
		return this.getHeaders();
	}
}
